﻿using Microsoft.AspNetCore.SignalR;

namespace Fortunate.API.hubs
{
    /// <summary>
    /// SignalR 长连接和集线器
    /// </summary>
    public class ChatHub : Hub<IChatClient>
    {
        //SignalR文档 https://learn.microsoft.com/zh-cn/aspnet/core/signalr/introduction?view=aspnetcore-5.0
        /// <summary>
        /// 连接
        /// </summary>
        /// <returns></returns>
        public override async Task OnConnectedAsync()
        {
            //在此可以获取token
            //var token = Context.GetHttpContext().Request.Query["access_token"];
            await base.OnConnectedAsync();
        }

        /// <summary>
        /// 断开
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        public override async Task OnDisconnectedAsync(Exception? exception)
        {
            //SignalR 为每个长连接生成的唯一连接id
            //Context.ConnectionId
            await base.OnConnectedAsync();
        }


        /// <summary>
        /// 此方法供客户端调用（前端调用）
        /// </summary>
        /// <returns></returns>
        public async Task SendMessage(string value)
        {
            //触发所有客户端代码
            await Clients.All.ReceiveMessage(value);
            //触发特定用户客户端
            await Clients.User("用户id").ReceiveMessage(value);
            //触发多个用户客户端 List<string>
            await Clients.Users("用户id", "用户id", "用户id").ReceiveMessage(value);
            //触发调用者客户端
            await Clients.Caller.ReceiveMessage(value);
            //触发除了调用者以外的客户端
            await Clients.Others.ReceiveMessage(value);
            //触发分组内客户端
            await Clients.Group("组").ReceiveMessage(value);
            //触发多个分组客户端 List<string>
            await Clients.Groups("组", "组", "组", "组").ReceiveMessage(value);
            //触发分组外的客户端
            await Clients.GroupExcept("组", "组", "组", "组").ReceiveMessage(value);
            
        }

    }
}

/// <summary>
/// 自定义用户唯一标识，需要在 Program.cs 中注册即可：
/// </summary>
public class YourUserIdProvider : IUserIdProvider
{
    //自定义用户唯一标识文档 https://docs.microsoft.com/zh-cn/aspnet/core/signalr/authn-and-authz?view=aspnetcore-6.0#use-claims-to-customize-identity-handling

    public virtual string GetUserId(HubConnectionContext connection)
    {
        // 你如何获取 UserId，可以通过 connection.User 获取 JWT 授权的用户
        //connection.GetHttpContext().Request.Query["token"].ToString();
        //connection.GetHttpContext().Request.Query[]
        //connection.GetHttpContext().Request.QueryString[]
        //connection.GetHttpContext().Response
        return "2212";
    }
}
